package com.huishao.demo.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huishao.demo.entity.vo.DailyFormAndKey;
import com.huishao.demo.entity.Key;
import com.huishao.demo.mapper.KeyMapper;
import com.huishao.demo.service.EmailService;
import com.huishao.demo.service.KeyService;
import com.huishao.demo.utils.PwdGenerate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.huishao.demo.common.EmailCommon.*;
import static com.huishao.demo.utils.IpUtil.getIpAddr;

/**
 * (Key)表服务实现类
 *
 * @author huishao
 * @since 2023-02-17 13:55:42
 */
@Service("keyService")
public class KeyServiceImpl extends ServiceImpl<KeyMapper, Key> implements KeyService {

    @Resource
    EmailService emailService;

    @Override
    public Key getByDate() {
        QueryWrapper<Key> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("create_time", getStringDate() + " 23:59:59");
        queryWrapper.ge("create_time", getStringDate() + " 00:00:00");
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1");
        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void insertKey(String key) {
        Key key1 = new Key();
        key1.setPassword(key);
        key1.setCreateTime(new Date());
        this.baseMapper.insert(key1);
    }

    // 获取日期并格式化为 yyyy-mm-dd
    public String getStringDate() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }

    @Override
    public boolean checkKey(DailyFormAndKey dailyFormAndKey,HttpServletRequest httpServletRequest) {
        String key = dailyFormAndKey.getKey();
        // 获取登录人ip
        String ip = getIpAddr(httpServletRequest);
        if("".equals(key)){
            emailService.sendSimpleMail(
                    MY_EMAIL,TO_EMAIL,CC,SERVER_SUBJECT,WRITE_FORMS_FAILURE+ip
            );
            return false;
        }
        // 加密
        try {
            String newKey = PwdGenerate.encryption(key);
            // 查询数据库 今日生成的key 是否和加密后的key一致
            if (newKey.equals(getByDate().getPassword())) {
                return true;
            }
        } catch (Exception e) {
            log.error("加密key失败！ 报错信息 ： " + e);
            emailService.sendSimpleMail(
                    MY_EMAIL,TO_EMAIL,CC,SERVER_SUBJECT,WRITE_FORMS_FAILURE+ip+" 报错信息 ： "+e
            );
            return false;
        }
        emailService.sendSimpleMail(
                MY_EMAIL,TO_EMAIL,CC,SERVER_SUBJECT,WRITE_FORMS_FAILURE+ip
        );
        return false;
    }


}

